/*
 * Copyright 2011-2012 by The Regents of the University of California Licensed
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. you may obtain a copy of the
 * License from
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package edu.ucsd.db.bassarisk.query.bindingtree.visitor;

import java.util.List;

import edu.ucsd.db.bassarisk.query.binding.Bindings.PositionBinding;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.BindingTreeEdge;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.ChoiceNode;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.ChoiceNode.Choice;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.ChoiceNode.ChooseAll;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.ChoiceNode.ChooseOne;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.EstablishingNode;
import edu.ucsd.db.bassarisk.treepattern.EdgeFunction;

public class MatchBindingCollectionTraversal implements
    BindingTreeVisitor<Void, List<PositionBinding>> {
  @Override
  public Void visitBindingTreeEdge(final BindingTreeEdge edge,
                                   final List<PositionBinding> args) {
    if (!(edge.functions().contains(EdgeFunction.Empty))) {
      edge.tailNode().accept(this, args);
    }
    return null;
  }

  @Override
  public Void visitChoiceNode(final ChoiceNode choices,
                              final List<PositionBinding> args) {
    for (Choice choice : choices.getChoices()) {
      if (choice instanceof ChooseOne) {
        ((ChooseOne) choice).getChild().accept(this, args);
      } else if (choice instanceof ChooseAll) {
        for (BindingTreeEdge edge : ((ChooseAll) choice).getChildren()) {
          edge.accept(this, args);
        }
      }
    }
    return null;
  }

  @Override
  public Void visitEstablishingNode(final EstablishingNode node,
                                    final List<PositionBinding> args) {
    if (node.getEstablishedBinding() instanceof PositionBinding) {
      args.add((PositionBinding) node.getEstablishedBinding());
    } else {
      for (BindingTreeEdge edge : node.children()) {
        edge.accept(this, args);
      }
    }
    return null;
  }
}
